<template>
  <div class="physical-stock-container">
    <div class="layout-container">
      <!-- 左侧菜单 -->
      <div class="left-menu">
        <el-tree
          :data="menuData"
          :props="defaultProps"
          @node-click="handleNodeClick"
          default-expand-all
          node-key="id"
          :highlight-current="true"
        />
      </div>
   
      <!-- 右侧内容 -->
      <div class="right-content">
        <!-- 查询条件 -->
        <div class="search-container">
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="产品物料编码">
              <el-input v-model="searchForm.materialCode" placeholder="请输入产品物料编码" />
            </el-form-item>
            <el-form-item label="产品物料名称">
              <el-input v-model="searchForm.materialName" placeholder="请输入产品物料名称" />
            </el-form-item>
            <el-form-item label="批次号">
              <el-input v-model="searchForm.batchNo" placeholder="请输入批次号" />
            </el-form-item>
            <el-form-item label="仓库名称">
              <el-input v-model="searchForm.warehouseName" placeholder="请输入仓库名称" />
            </el-form-item>
            <el-form-item label="库位编码">
              <el-input v-model="searchForm.locationCode" placeholder="请输入库位编码" />
            </el-form-item>
            <el-form-item label="是否冻结">
              <el-select v-model="searchForm.isFrozen" placeholder="请选择" style="width: 180px;">
                <el-option label="是" value="1" />
                <el-option label="否" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" class="action-button" @click="search">搜索</el-button>
              <el-button :icon="Refresh" class="action-button" @click="reset">重置</el-button>
              <el-button type="warning" :icon="Download" class="action-button" @click="exportData">导出</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 数据表格 -->
        <el-table
          :data="tableData"
          style="width: 100%"
          border
          :height="660"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="materialCode" label="产品物料编码" width="150" />
          <el-table-column prop="materialName" label="产品物料名称" width="150" />
          <el-table-column prop="specType" label="规格型号" width="120" />
          <el-table-column prop="inventoryQuantity" label="在库数量" width="100" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="lotNum" label="批次号" width="120" />
          <el-table-column prop="depot" label="仓库" width="120" />
          <el-table-column prop="galleryArea" label="库区" width="120" />
          <el-table-column prop="binLocation" label="库位" width="120" />
          <el-table-column prop="createTime" label="入库日期" width="120">
            <template #default="{ row }">
              <span>{{ formatDate(row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否冻结" width="120" align="center">
            <template #default="{ row }">
              <div v-if="row" class="freeze-switch-container">
                <span class="freeze-label" :class="{'active': !row.isFrozen}">否</span>
                <el-switch
                  v-model="row.isFrozen"
                  @change="() => handleFrozenChange(row)"
                />
                <span class="freeze-label" :class="{'active': row.isFrozen}">是</span>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus' 
import axios from 'axios'

// 类型定义
interface MenuItem {
  id: string
  label: string
  type: string
  materialCode?: string
  children?: MenuItem[]
}

interface SearchForm {
  materialCode: string
  materialName: string
  batchNo: string
  warehouseName: string
  locationCode: string
  isFrozen: string
  MaterialCode?: string
}

interface MaterialItem {
  materialCode: string
  materialName: string
  spec: string
  quantity: number
  unit: string
  batchNo: string
  warehouse: string
  location: string
  position: string
  inDate: string
  isFrozen: boolean
  category: string
  material: string
}

// 左侧菜单数据
const menuData = ref<MenuItem[]>([])

// 获取树形菜单数据
const fetchMenuData = async () => {
  try {
    const res = await axios.get('/api/PhysicalStock/GetMenu')
    menuData.value = res.data
  } catch (e) {
    console.error('获取树形菜单失败', e)
  }
}

const defaultProps = {
  children: 'children',
  label: 'label'
}

// 查询表单
const searchForm = reactive<SearchForm>({
  materialCode: '',
  materialName: '',
  batchNo: '',
  warehouseName: '',
  locationCode: '',
  isFrozen: ''
})

// 实际查询条件
const searchQuery = reactive<SearchForm>({
  materialCode: '',
  MaterialCode: '',
  materialName: '',
  batchNo: '',
  warehouseName: '',
  locationCode: '',
  isFrozen: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableHeight = ref(500)
const currentNode = ref<MenuItem | null>(null)

// 表格数据
const tableData = ref<MaterialItem[]>([])

// 获取表格数据
const fetchTableData = () => {
  // 构造符合后端要求的参数对象
  const params = {
    MaterialCode: searchQuery.MaterialCode || '',
    MaterialName: searchQuery.materialName,
    BatchNo: searchQuery.batchNo,
    WarehouseName: searchQuery.warehouseName,
    LocationCode: searchQuery.locationCode,
    IsFrozen: searchQuery.isFrozen === '' ? null : searchQuery.isFrozen === '1',
    Page: currentPage.value,
    PageSize: pageSize.value
  }

  console.log('发送到后台的参数:', params)

  axios.get('/api/PhysicalStock/Search', { params })
  .then(res => {
    console.log('后台返回数据:', res.data)
    tableData.value = Array.isArray(res.data.data) ? res.data.data : []
    total.value = res.data.totalCount || 0
  })
  .catch((error) => {
    console.error('请求失败:', error)
    tableData.value = []
    total.value = 0
  })
}

// 分页后的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return tableData.value.slice(start, end)
})

// 处理节点点击，联动右侧表格
const handleNodeClick = (data: MenuItem) => {
  console.log('点击的节点数据:', data)
  currentNode.value = data
  // 更新搜索条件中的 materialCodeFilter
  if (data.materialCode) {
    searchQuery.MaterialCode = data.materialCode
    console.log('设置的 MaterialCode:', data.materialCode)
  }
  currentPage.value = 1
  search() // 统一调用搜索，带上所有条件
}

// 查询功能，带上所有条件和分页
const search = () => {
  // 保持树形选择的 materialCode
  const treeNodeMaterialCode = currentNode.value?.materialCode
  
  // 合并搜索表单数据
  Object.assign(searchQuery, {
    ...searchForm,
    MaterialCode: treeNodeMaterialCode || searchForm.materialCode
  })
  
  console.log('搜索参数:', searchQuery)
  fetchTableData()
}

// 重置功能
const reset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key as keyof SearchForm] = ''
  })
  
  // 保持树形选择的 materialCode
  const treeNodeMaterialCode = currentNode.value?.materialCode
  
  Object.assign(searchQuery, {
    ...searchForm,
    MaterialCode: treeNodeMaterialCode || ''
  })
  
  currentPage.value = 1
  fetchTableData()
}

// 处理每页显示数量变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchTableData()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchTableData()
}

// 处理冻结状态变化
const handleFrozenChange = (row: MaterialItem) => {
  if (!row) return
  console.log('冻结状态改变:', row)
  // 这里可以添加调用后端API的逻辑
  ElMessage({
    type: 'success',
    message: `${row.materialName} 冻结状态已更新为: ${row.isFrozen ? '是' : '否'}`
  })
}

// 切换冻结状态
const toggleFrozenStatus = (row: MaterialItem) => {
  if (!row) return
  row.isFrozen = !row.isFrozen
  handleFrozenChange(row)
}

// 导出数据
const exportData = () => {
  // 实现导出逻辑
  console.log('导出数据:', tableData.value)
}

// 日期格式化函数，只显示年月日
function formatDate(dateStr: string) {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}

// 组件挂载时
onMounted(() => {
  fetchMenuData()
  fetchTableData()
  // 计算表格高度
  tableHeight.value = window.innerHeight - 280
  // 初始加载数据
  fetchTableData()

  // 添加窗口大小变化监听
  const handleResize = () => {
    tableHeight.value = window.innerHeight - 280
  }
  window.addEventListener('resize', handleResize)
  // 清理函数
  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
  })
})

</script>

<style lang="scss" scoped>
.physical-stock-container {
  height: 100%;
  background: white;
  
  .layout-container {
    display: flex;
    height: 100%;

    .left-menu {
      width: 200px;
      padding: 10px;
      border-right: 1px solid #e0e0e0;
      height: 100%;
      overflow-y: auto;
      background-color: #fff;
    }

    .right-content {
      flex: 1;
      padding: 15px;
      display: flex;
      flex-direction: column;

      .search-container {
        background: #fff;
        padding: 15px;
        margin-bottom: 15px;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);

        .search-form {
          .el-form-item {
            margin-bottom: 10px;
          }
        }
      }

      .pagination-container {
        margin-top: 15px;
        text-align: right;
      }
    }
  }

  .action-button {
    min-width: 90px;
    text-align: center;
  }
  
  .freeze-switch-container {
    display: flex;
    align-items: center;
    justify-content: center;
    
    .freeze-label {
      font-size: 14px;
      color: #909399;
      margin: 0 5px;
      transition: all 0.3s;
      
      &.active {
        color: #409EFF;
        font-weight: 500;
      }
    }
  }
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
  color: #409EFF;
}
</style>
